<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="思路指南数据结构的存储方式其实只有两种，顺序存储（数组）和链式存储（链表），要有递归的思想，自顶而下，从抽象到具体； 队列、栈：用数组实现，要处理扩容、缩容问题；用链表实现，需要更多内存空间存储节点指针； 图：用二维数组实现，邻接矩阵，判断连通性迅速单图如果稀疏则会耗费时间；链表实现：邻接表，节省空间，但操作效率不够； 散列表：通过散列函数将键映射到一个大数组中，拉链法：链表特性，操作简单但需要额">
<meta property="og:type" content="article">
<meta property="og:title" content="二叉树算法">
<meta property="og:url" content="http://example.com/2020/09/06/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%AE%97%E6%B3%95/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="思路指南数据结构的存储方式其实只有两种，顺序存储（数组）和链式存储（链表），要有递归的思想，自顶而下，从抽象到具体； 队列、栈：用数组实现，要处理扩容、缩容问题；用链表实现，需要更多内存空间存储节点指针； 图：用二维数组实现，邻接矩阵，判断连通性迅速单图如果稀疏则会耗费时间；链表实现：邻接表，节省空间，但操作效率不够； 散列表：通过散列函数将键映射到一个大数组中，拉链法：链表特性，操作简单但需要额">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-09-06T08:12:42.000Z">
<meta property="article:modified_time" content="2021-11-03T08:30:41.274Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="算法框架">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2020/09/06/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%AE%97%E6%B3%95/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>二叉树算法 | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2020/09/06/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%AE%97%E6%B3%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          二叉树算法
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2020-09-06 16:12:42" itemprop="dateCreated datePublished" datetime="2020-09-06T16:12:42+08:00">2020-09-06</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:30:41" itemprop="dateModified" datetime="2021-11-03T16:30:41+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">算法</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="思路指南"><a href="#思路指南" class="headerlink" title="思路指南"></a>思路指南</h1><h2 id="数据结构的存储方式"><a href="#数据结构的存储方式" class="headerlink" title="数据结构的存储方式"></a>数据结构的存储方式</h2><p>其实只有两种，顺序存储（数组）和链式存储（链表），要有递归的思想，自顶而下，从抽象到具体；</p>
<p>队列、栈：用数组实现，要处理扩容、缩容问题；用链表实现，需要更多内存空间存储节点指针；</p>
<p>图：用二维数组实现，邻接矩阵，判断连通性迅速单图如果稀疏则会耗费时间；链表实现：邻接表，节省空间，但操作效率不够；</p>
<p>散列表：通过散列函数将键映射到一个大数组中，拉链法：链表特性，操作简单但需要额外空间存储指针；线性探查法：数组特性，以便连续寻址，不需要指针存储空间但操作复杂；</p>
<p>树：用数组实现：堆，完全二叉树；链表实现，正常二叉树，二叉搜索树、AVL树、红黑树、区间树、B树；</p>
<h3 id="二者优缺点"><a href="#二者优缺点" class="headerlink" title="二者优缺点"></a>二者优缺点</h3><p>数组：紧凑连续存储，可以随机访问，通过索引快速搜索，相对节省空间，但需要一次分别配够空间，若需要扩容，则重新分配空间并拷贝过去，T(n) = O(n)，且每次进行插入与删除时，必须搬移后面所有数据以保持连续，T(n) = O(N)。</p>
<p>链表：元素不连续，靠指针指向下一个元素的位置，故不存在数组的扩容问题；在知道前驱、后驱时操作指针插入、删除的T(n)=O(1)，但同样因为不连续从而不能根据索引计算对应元素地址，无法随机访问，同样会消耗更多存储空间。</p>
<h3 id="基本操作"><a href="#基本操作" class="headerlink" title="基本操作"></a>基本操作</h3><p>遍历+访问；具体为：增删改查。</p>
<p>线性的，以for/while迭代为代表；</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">traverse</span><span class="params">(<span class="keyword">int</span>[] arr)</span> </span>&#123; </span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; arr.length; i++) &#123; </span><br><span class="line">        <span class="comment">// 迭代访问 arr[i] </span></span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>链表遍历框架，兼具迭代与递归</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 基本的单链表节点 */</span> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ListNode</span> &#123;</span> </span><br><span class="line">    <span class="keyword">int</span> val; </span><br><span class="line">    ListNode next; </span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">traverse</span><span class="params">(ListNode head)</span> </span>&#123; </span><br><span class="line">    <span class="keyword">for</span> (ListNode p = head; p != null; p = p.next) &#123; </span><br><span class="line">        <span class="comment">// 迭代访问 p.val </span></span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">traverse</span><span class="params">(ListNode head)</span> </span>&#123; </span><br><span class="line">    <span class="comment">// 递归访问 head.val </span></span><br><span class="line">    traverse(head.next);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>二叉树遍历框架：典型的非线性递归遍历结构</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 基本的⼆叉树节点 */</span> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TreeNode</span> &#123;</span> </span><br><span class="line">    <span class="keyword">int</span> val; </span><br><span class="line">    TreeNode left, right; </span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">traverse</span><span class="params">(TreeNode root)</span> </span>&#123; </span><br><span class="line">    traverse(root.left); </span><br><span class="line">    traverse(root.right); </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>N叉树的遍历：非线性递归</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 基本的 N 叉树节点 */</span> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TreeNode</span> &#123;</span> </span><br><span class="line">    <span class="keyword">int</span> val; </span><br><span class="line">    TreeNode[] children; </span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">traverse</span><span class="params">(TreeNode root)</span> </span>&#123; </span><br><span class="line">    <span class="keyword">for</span> (TreeNode child : root.children) </span><br><span class="line">        traverse(child);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>N叉树的遍历可扩展为图的遍历，如何实现图的环？：用个布尔数组visited做标记。</p>
<p>你就会发现只要涉及递归的问题，都是树的问题；其实很多动态规划问题就是在遍历⼀棵树，你如果对树的遍历操作烂熟于心，起码知道怎么把思路转化成代码，也知道如何提取别⼈解法的核⼼思 路。再看看回溯算法，前⽂回溯算法详解⼲脆直接说了，回溯算法就是个 N 叉 树的前后序遍历问题，没有例外。</p>
<h1 id="medium二叉树刷题（树的核心是递归遍历）"><a href="#medium二叉树刷题（树的核心是递归遍历）" class="headerlink" title="medium二叉树刷题（树的核心是递归遍历）"></a>medium二叉树刷题（树的核心是递归遍历）</h1><h2 id="二叉树中序遍历"><a href="#二叉树中序遍历" class="headerlink" title="二叉树中序遍历"></a>二叉树中序遍历</h2><p>方法一：基于栈的遍历</p>
<p>1、如果left节点存在，就入栈，然后跳left；</p>
<p>2、如果left和right都不存在，则保存当前节点，然后出栈，并让left等于null；</p>
<p>3、如果right存在，且left不存在，则保存当前节点，然后跳right。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"> * function TreeNode(val) &#123;</span></span><br><span class="line"><span class="comment"> *     this.val = val;</span></span><br><span class="line"><span class="comment"> *     this.left = this.right = null;</span></span><br><span class="line"><span class="comment"> * &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;TreeNode&#125;</span> <span class="variable">root</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;number[]&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">// 中序遍历</span></span><br><span class="line"><span class="keyword">const</span> inorderTraversal = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> list = [];</span><br><span class="line">    <span class="keyword">let</span> stack = [];</span><br><span class="line">    <span class="keyword">let</span> node = root;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span>(node || stack.length) &#123;</span><br><span class="line">    <span class="comment">// 遍历左子树</span></span><br><span class="line">      <span class="keyword">while</span>(node) &#123;</span><br><span class="line">          stack.push(node);</span><br><span class="line">          node = node.left;</span><br><span class="line">      &#125;</span><br><span class="line">        node = stack.pop();</span><br><span class="line">        list.push(node.val);</span><br><span class="line">        node = node.right;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> list;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> inorderTraversal = <span class="function"><span class="params">root</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> res = [], stack = []</span><br><span class="line">  <span class="keyword">while</span> (root || stack.length) &#123;</span><br><span class="line">    <span class="keyword">if</span> (root.left) &#123;</span><br><span class="line">      stack.push(root)；</span><br><span class="line">      root = root.left；</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!root.left &amp;&amp; !root.right) &#123;</span><br><span class="line">      res.push(root.val)；</span><br><span class="line">      root = stack.pop()；</span><br><span class="line">      root &amp;&amp; (root.left = <span class="literal">null</span>)；</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (root.right) &#123;</span><br><span class="line">      res.push(root.val)；</span><br><span class="line">      root = root.right；</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>方法二：递归</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> inorderTraversal = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> arr = [];</span><br><span class="line">    <span class="keyword">if</span>(!root) <span class="keyword">return</span> [];</span><br><span class="line"></span><br><span class="line">   <span class="keyword">let</span> nums = [root];</span><br><span class="line">    <span class="comment">//递归方法实现</span></span><br><span class="line">    MiddleOrder(root,arr);</span><br><span class="line">    <span class="keyword">return</span> arr;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">MiddleOrder</span>(<span class="params">root,arr</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(root.left)&#123;</span><br><span class="line">        MiddleOrder(root.left,arr);</span><br><span class="line">    &#125;</span><br><span class="line">    arr.push(root.val);</span><br><span class="line">    <span class="keyword">if</span>(root.right)&#123;</span><br><span class="line">        MiddleOrder(root.right,arr);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="前序遍历二叉树"><a href="#前序遍历二叉树" class="headerlink" title="前序遍历二叉树"></a>前序遍历二叉树</h2><p>方法一：基于栈的迭代实现</p>
<p>首先根入栈将根节点出栈，将根节点值放入结果数组中</p>
<p>然后遍历左子树、右子树，因为栈是先入后出，所以，我们先右子树入栈，然后左子树入栈</p>
<p>继续出栈（左子树被出栈）…….</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 前序遍历</span></span><br><span class="line"><span class="keyword">const</span> preorderTraversal = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> list = [];</span><br><span class="line">    <span class="keyword">const</span> stack = [];</span><br><span class="line">    <span class="keyword">let</span> node = root;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> (node || stack.length)&#123;</span><br><span class="line">        <span class="keyword">while</span> (node)&#123;</span><br><span class="line">            stack.push(node.right);</span><br><span class="line">            list.push(node.val);</span><br><span class="line">            node = node.left;</span><br><span class="line">        &#125;</span><br><span class="line">        node = stack.pop();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> list;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 前序遍历</span></span><br><span class="line"><span class="keyword">var</span> preorderTraversal = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> result = []</span><br><span class="line">    <span class="keyword">var</span> preOrderTraverseNode = <span class="function">(<span class="params">node</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(node) &#123;</span><br><span class="line">            <span class="comment">// 先根节点</span></span><br><span class="line">            result.push(node.val)</span><br><span class="line">            <span class="comment">// 然后遍历左子树</span></span><br><span class="line">            preOrderTraverseNode(node.left)</span><br><span class="line">            <span class="comment">// 再遍历右子树</span></span><br><span class="line">            preOrderTraverseNode(node.right)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    preOrderTraverseNode(root)</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="后序遍历二叉树"><a href="#后序遍历二叉树" class="headerlink" title="后序遍历二叉树"></a>后序遍历二叉树</h2><p>按照左子树-根-右子树的方式，将其转换成迭代方式。</p>
<p>思路：每到一个节点 A，因为根要最后访问，将其入栈。然后遍历左子树，遍历右子树，最后返回到 A。</p>
<p>但是出现一个问题，无法区分是从左子树返回，还是从右子树返回。</p>
<p>因此，给 A 节点附加一个标记T。在访问其右子树前，T 置为 True。之后子树返回时，当 T 为 True表示从右子树返回，否则从左子树返回。</p>
<p>当 T 为 false 时，表示 A 的左子树遍历完，还要访问右子树。</p>
<p>同时，当 T 为 True 时，表示 A 的两棵子树都遍历过了，要访问 A 了。并且在 A 访问完后，A 这棵子树都访问完成了。</p>
<p>1, 先遍历左节点, 当遍历到末尾节点时, 记录值</p>
<p>2, 然后跳回上一层节点, 顺便让left等于null</p>
<p>3, 再遍历右节点, 同样是遍历到末尾节点时, 记录值</p>
<p>4, 第二次返回时, 让右节点等于null</p>
<p>通过这种人为的方式，不断创造末尾节点值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> postorderTraversal = <span class="function"><span class="params">root</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> res = [], stack = [];</span><br><span class="line">  <span class="keyword">while</span> (root || stack.length) &#123;</span><br><span class="line">    <span class="keyword">if</span> (root.left) &#123;</span><br><span class="line">      stack.push(root);</span><br><span class="line">      root = root.left;</span><br><span class="line">    &#125; </span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (root.right) &#123;</span><br><span class="line">      stack.push(root);</span><br><span class="line">      root = root.right;</span><br><span class="line">    &#125; </span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">      res.push(root.val);</span><br><span class="line">      root = stack.pop();</span><br><span class="line">      <span class="keyword">if</span> (root &amp;&amp; root.left) root.left = <span class="literal">null</span>;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (root &amp;&amp; root.right) root.right = <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="不同的二叉搜索树"><a href="#不同的二叉搜索树" class="headerlink" title="不同的二叉搜索树"></a>不同的二叉搜索树</h2><p>给定一个整数 <em>n</em>，求以 1 … <em>n</em> 为节点组成的二叉搜索树有多少种？</p>
<p>思路：动态规划；为了构建一颗二叉搜索树，可以遍历每一个数字i,将其作为树根，并将1…i-1作为左子树，i+1…n作为右子树，接着可以按照同样方式递归构建左右子树。原问题可以分成规模较小的两个子问题，且解可以复用，因此用动态规划处理。</p>
<p>具体步骤：题目要求是计算不同二叉搜索树的个数。为此，我们可以定义两个函数：G(n): 长度为 n 的序列能构成的不同二叉搜索树的个数。F(i, n): 以 i 为根、序列长度为 n 的不同二叉搜索树个数 (1 \leq i \leq n)(1≤i≤n)。可见，G(n) 是我们求解需要的函数。</p>
<p>动态规划问题的关键在于构建状态转移方程。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> numTrees = <span class="function"><span class="keyword">function</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> G = <span class="keyword">new</span> <span class="built_in">Array</span>(n + <span class="number">1</span>).fill(<span class="number">0</span>);</span><br><span class="line">    G[<span class="number">0</span>] = <span class="number">1</span>;</span><br><span class="line">    G[<span class="number">1</span>] = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">2</span>; i &lt;= n; ++i) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">1</span>; j &lt;= i; ++j) &#123;</span><br><span class="line">            G[i] += G[j - <span class="number">1</span>] * G[i - j];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> G[n];</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>在本题目的扩展下，如果要求生成所有由1-n节点所组成的二叉搜索树。</p>
<p>和二叉搜索树一的解法不同，一的目的是求数量，而这道题是求具体的解，所以不能从树的规律来简化；利用树的递归特性，采用DFS来递归求解；</p>
<p>n个数组成的二叉树，分为分别以1,2,3…,n为顶点的树；以i为例：f[i]的左边树就是1到i-1个数组成的二叉搜索树，因为左边的节点都比顶点小；f[i]的右边子树就是[i+1]到n的数组成的二叉搜索树，因为右边的节点都比顶点大；左右两侧都是树的数组；组合之后，f[i]的数组组合就得到了。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"> * function TreeNode(val, left, right) &#123;</span></span><br><span class="line"><span class="comment"> *     this.val = (val===undefined ? 0 : val)</span></span><br><span class="line"><span class="comment"> *     this.left = (left===undefined ? null : left)</span></span><br><span class="line"><span class="comment"> *     this.right = (right===undefined ? null : right)</span></span><br><span class="line"><span class="comment"> * &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> <span class="variable">n</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;TreeNode[]&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> generateTrees = <span class="function"><span class="keyword">function</span> (<span class="params">n</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (n == <span class="number">0</span>) <span class="keyword">return</span> [];</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">getTree</span>(<span class="params">s, e</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (s &gt; e) <span class="keyword">return</span> [<span class="literal">null</span>];</span><br><span class="line">        <span class="keyword">if</span> (s == e) <span class="keyword">return</span> [<span class="keyword">new</span> TreeNode(s)];</span><br><span class="line">        <span class="keyword">var</span> tree = [];</span><br><span class="line">        <span class="keyword">var</span> i = s;</span><br><span class="line">        <span class="keyword">while</span> (i &lt;= e) &#123;</span><br><span class="line">            <span class="keyword">var</span> lefts = getTree(s, i - <span class="number">1</span>), rights = getTree(i + <span class="number">1</span>, e);</span><br><span class="line">            <span class="keyword">while</span> (lefts.length) &#123;</span><br><span class="line">                <span class="keyword">var</span> left = lefts.pop(), j = <span class="number">0</span>;</span><br><span class="line">                <span class="keyword">while</span> (j &lt; rights.length) &#123;</span><br><span class="line">                    <span class="keyword">var</span> right = rights[j];</span><br><span class="line">                    j++;</span><br><span class="line">                    <span class="keyword">var</span> node = <span class="keyword">new</span> TreeNode(i);</span><br><span class="line">                    node.left = left;</span><br><span class="line">                    node.right = right;</span><br><span class="line">                    tree.push(node);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            i++;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> tree;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> getTree(<span class="number">1</span>, n);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>从构建1棵树到构建n棵树，该递归思路其实清晰可见。</p>
<h2 id="验证二叉搜索树"><a href="#验证二叉搜索树" class="headerlink" title="验证二叉搜索树"></a>验证二叉搜索树</h2><p>给定一个二叉树，判断其是否是一个有效的二叉搜索树。假设一个二叉搜索树具有如下特征：1、节点的左子树只包含小于当前节点的数。2、节点的右子树只包含大于当前节点的数。3、所有左子树和右子树自身必须也是二叉搜索树。</p>
<p>方法一：设计一个递归函数来判断，函数表示考虑以root为跟的子树，其子树所有节点是否都在（l,r）的范围内。不在则直接返回，在的话则继续递归调用其左右子树是否满足。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> helper = <span class="function">(<span class="params">root, lower, upper</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="literal">null</span>) <span class="keyword">return</span> ture;</span><br><span class="line">    <span class="keyword">if</span> (root.val &lt;= lower || root.val &gt;= upper) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">return</span> helper(root.left, lower, root.val) &amp;&amp; helper(root.right, root.val, upper);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> isValidBST = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> helper(root, -<span class="literal">Infinity</span>, <span class="literal">Infinity</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>方法二：中序遍历，二叉搜索树的中序遍历结果一定是升序序列。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> isValidBST = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> stack = [];</span><br><span class="line">    <span class="keyword">let</span> inorder = -<span class="literal">Infinity</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> (stack.length || root !== <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">while</span> (root !== <span class="literal">null</span>) &#123;</span><br><span class="line">            stack.push(root);</span><br><span class="line">            root = root.left;</span><br><span class="line">        &#125;</span><br><span class="line">        root = stack.pop();</span><br><span class="line">        <span class="comment">// 如果中序遍历得到的节点的值小于等于前一个 inorder，说明不是二叉搜索树</span></span><br><span class="line">        <span class="keyword">if</span> (root.val &lt;= inorder) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        inorder = root.val;</span><br><span class="line">        root = root.right;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="对称二叉树"><a href="#对称二叉树" class="headerlink" title="对称二叉树"></a>对称二叉树</h2><p>验证一个二叉树是否对称</p>
<p>方法一：递归；左子树和右子树镜像对称则这个树是对称的，1、根节点的值相同；2、一个树的右子树跟另一个树的左子树镜像对称。其实本质跟二叉树相等的递归一样。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> isSymmetric = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> check = <span class="function">(<span class="params">left, right</span>) =&gt;</span> &#123; </span><br><span class="line">    <span class="keyword">if</span> (left == <span class="literal">null</span> &amp;&amp; right == <span class="literal">null</span>) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">if</span> (left &amp;&amp; right) &#123;</span><br><span class="line">      <span class="keyword">return</span> left.val == right.val &amp;&amp;</span><br><span class="line">        check(left.left, right.right) &amp;&amp;</span><br><span class="line">        check(left.right, right.left);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (root) &#123;</span><br><span class="line">    <span class="keyword">return</span> check(root.left, root.right);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>方法二：BFS广度遍历法；入队列的顺序：1、左子树的左子树，右子树的右子树；2、左子树的右子树，右子树的左子树；出队列的时候，检查两两是否对称。</p>
<p>JS中array类型提供了pop()和push()方法来模仿栈这个数据结构的方法；push()方法接受任意数量的参数，并将其逐个添加到数组尾部，并返回修改后数组的长度；pop()方法则从数组末尾溢出最后一项，减少数组的length值，然后返回溢出的项。</p>
<p>而JS用push()和shift()方法结合来模仿队列；shift()方法溢出数组中的第一项并返回该项，同时将数组长度减一；同时也提供了unshift()方法，能在数组前端添加任意项并返回新数组的长度。因此同时使用unshift()和pop()可以从相反方向模拟数列，在前端添加项，从末端移除项。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> isSymmetric = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (root == <span class="literal">null</span>) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> leftQueue = [root.left];   <span class="comment">// 队列存放左子树</span></span><br><span class="line">  <span class="keyword">const</span> rightQueue = [root.right]; <span class="comment">// 队列存放右子树</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span> (leftQueue.length &amp;&amp; rightQueue.length) &#123;</span><br><span class="line">    <span class="keyword">const</span> left = leftQueue.shift();</span><br><span class="line">    <span class="keyword">const</span> right = rightQueue.shift();</span><br><span class="line">    <span class="comment">// 左右子树都为空，没有子节点可入列，continue</span></span><br><span class="line">    <span class="keyword">if</span> (left == <span class="literal">null</span> &amp;&amp; right == <span class="literal">null</span>) &#123;</span><br><span class="line">      <span class="keyword">continue</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> ((left == <span class="literal">null</span> &amp;&amp; right) || (left &amp;&amp; right == <span class="literal">null</span>)) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (left.val != right.val) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    leftQueue.push(left.left);</span><br><span class="line">    rightQueue.push(right.right);</span><br><span class="line">    leftQueue.push(left.right);</span><br><span class="line">    rightQueue.push(right.left);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 其中一个子树还有节点没遍历，说明不对称</span></span><br><span class="line">  <span class="keyword">if</span> (leftQueue.length || leftQueue.length) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>方法三：利用两个栈来对递归进行模拟</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> isSymmetric = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (!root) <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">  <span class="keyword">let</span> leftStack = [], rightStack = [] <span class="comment">// 维护两个栈</span></span><br><span class="line">  <span class="keyword">let</span> curLeft = root.left             <span class="comment">// 当前的左子树</span></span><br><span class="line">  <span class="keyword">let</span> curRight = root.right           <span class="comment">// 当前的右子树</span></span><br><span class="line">  <span class="keyword">while</span> (curLeft || curRight || leftStack.length || rightStack.length) &#123;</span><br><span class="line">    <span class="keyword">while</span> (curLeft) &#123;         <span class="comment">// 左子树存在</span></span><br><span class="line">      leftStack.push(curLeft) <span class="comment">// 推入leftStack栈</span></span><br><span class="line">      curLeft = curLeft.left  <span class="comment">// 不断将左子树入栈</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (curRight) &#123;          <span class="comment">// 右子树存在</span></span><br><span class="line">      rightStack.push(curRight) <span class="comment">// 推入rightStack栈</span></span><br><span class="line">      curRight = curRight.right <span class="comment">// 不断将右子树压入栈</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (leftStack.length !== rightStack.length) <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">                                <span class="comment">// 栈的高度不相等，说明结构不对称</span></span><br><span class="line">    curLeft = leftStack.pop()   <span class="comment">// 栈顶节点出栈，赋给curLeft</span></span><br><span class="line">    curRight = rightStack.pop() <span class="comment">// 栈顶节点出栈，赋给curRight</span></span><br><span class="line">    <span class="keyword">if</span> (curLeft.val !== curRight.val) <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">                                <span class="comment">// 两个栈出栈的节点值不相等 不对称</span></span><br><span class="line">    curLeft = curLeft.right     <span class="comment">// 考察左子树的right</span></span><br><span class="line">    curRight = curRight.left    <span class="comment">// 考察右子树的left</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="二叉树的BFS与DFS"><a href="#二叉树的BFS与DFS" class="headerlink" title="二叉树的BFS与DFS"></a>二叉树的BFS与DFS</h2><p>DFS：深度优先搜索一般使用递归的方法进行实现。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> dfs = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="literal">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> ;</span><br><span class="line">    &#125;</span><br><span class="line">    dfs(root.left);</span><br><span class="line">    dfs(root.right);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>BFS则是使用队列的数据结构来进行遍历；</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> dfs = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> queue = [];</span><br><span class="line">    queue.push(root);</span><br><span class="line">    <span class="keyword">while</span> (queue.length != <span class="number">0</span>)&#123;</span><br><span class="line">        <span class="keyword">var</span> node = queue.shift();</span><br><span class="line">        <span class="keyword">if</span> (node.left != <span class="literal">null</span>)&#123;</span><br><span class="line">            queue.push(node.left);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (node.right != <span class="literal">null</span>)&#123;</span><br><span class="line">            queue.push(node.right);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>递归的方法其实隐含地使用了系统的栈，不需要自己去维护数据结构；BFS这种独特的遍历方式正式其用于求解层序遍历和最短路径问题的根本原因。</p>
<h2 id="层序遍历与最小路径问题"><a href="#层序遍历与最小路径问题" class="headerlink" title="层序遍历与最小路径问题"></a>层序遍历与最小路径问题</h2><p>1、层序遍历；利用BFS遍历二叉树无法区分队列中的节点来自哪一层，因此需要修改下代码记录队列中节点数量n（即这一层的节点数），然后一口气处理该层n个节点。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> dfs = <span class="function">(<span class="params">root</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> queue = [], res = [], level = [];</span><br><span class="line">    queue.push(root);</span><br><span class="line">    <span class="keyword">while</span> (queue.length != <span class="number">0</span>)&#123;</span><br><span class="line">        <span class="keyword">var</span> n = queue.length;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; n; i++)&#123;</span><br><span class="line">        	<span class="keyword">var</span> node = queue.shift();</span><br><span class="line">            level.push(node.val);</span><br><span class="line">        	<span class="keyword">if</span> (node.left != <span class="literal">null</span>)&#123;</span><br><span class="line">            	queue.push(node.left);</span><br><span class="line">        	&#125;</span><br><span class="line">        	<span class="keyword">if</span> (node.right != <span class="literal">null</span>)&#123;</span><br><span class="line">            	queue.push(node.right);</span><br><span class="line">        	&#125;</span><br><span class="line">        &#125;</span><br><span class="line">        res.pop(level);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其实根据上述层序遍历的代码，要实现二叉树层序遍历的反向输出，只需要修改最后res的入队列方式即可，用unshift来代替pop。</p>
<p>2、最短路径问题：在树中一个节点到一个节点的路径是唯一的，但在图中可能有多条路径，找寻哪一条路径最短。在BFS中，距离源点越近的点会先被遍历到。（Dijkstra算法解决的是带权最短路径问题，而BFS解决的是无权最短路径问题）</p>
<h2 id="二叉树的锯齿形层次遍历"><a href="#二叉树的锯齿形层次遍历" class="headerlink" title="二叉树的锯齿形层次遍历"></a>二叉树的锯齿形层次遍历</h2><p>给定一个二叉树，返回其节点值的锯齿形层次遍历。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）</p>
<p>思路：典型广度优先题目；广度优先通过队列处理 【深度优先用栈】</p>
<p>1、将一层记录在数组中 并记录数组长度找下一行所有数据将数组首位弹出 将首位的左右节点追在数组后；</p>
<p>2、按照记录的数组长度 将上层的结点全部弹出后 此时数组只剩下下一行结点了 此时就完成了一层的遍历；类似上题 与上题区别 每层输出反向 加个条件即可</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">* @<span class="keyword">return</span> &#123;number[][]&#125;</span><br><span class="line"> *</span><br><span class="line"><span class="keyword">var</span> zigzagLevelOrder = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(root==<span class="literal">null</span>)</span><br><span class="line">    <span class="keyword">return</span> []</span><br><span class="line">  <span class="keyword">var</span> arr=[root]</span><br><span class="line">  <span class="keyword">var</span> res=[]</span><br><span class="line">  <span class="keyword">var</span> go=<span class="literal">true</span></span><br><span class="line">  <span class="keyword">while</span>(arr.length&gt;<span class="number">0</span>)&#123;</span><br><span class="line">    <span class="keyword">var</span> n=arr.length</span><br><span class="line">    <span class="keyword">var</span> now=[]</span><br><span class="line">    <span class="keyword">if</span>(go)&#123;</span><br><span class="line">      <span class="keyword">while</span>(n--&gt;<span class="number">0</span>)&#123;</span><br><span class="line">        <span class="keyword">var</span> node=arr.shift()</span><br><span class="line">        now.push(node.val)</span><br><span class="line">        <span class="keyword">if</span>(node.left!=<span class="literal">null</span>)arr.push(node.left)</span><br><span class="line">        <span class="keyword">if</span>(node.right!=<span class="literal">null</span>)arr.push(node.right)</span><br><span class="line">      &#125;</span><br><span class="line">      res.push(now)</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">      <span class="keyword">while</span>(n--&gt;<span class="number">0</span>)&#123;</span><br><span class="line">        <span class="keyword">var</span> node=arr.pop()</span><br><span class="line">        now.push(node.val)</span><br><span class="line">        <span class="keyword">if</span>(node.right!=<span class="literal">null</span>)arr.unshift(node.right)</span><br><span class="line">        <span class="keyword">if</span>(node.left!=<span class="literal">null</span>)arr.unshift(node.left)</span><br><span class="line">      &#125;</span><br><span class="line">      res.push(now)</span><br><span class="line">    &#125;</span><br><span class="line">    go=!go</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>





<h2 id="前序跟中序遍历构造二叉树"><a href="#前序跟中序遍历构造二叉树" class="headerlink" title="前序跟中序遍历构造二叉树"></a>前序跟中序遍历构造二叉树</h2><p>思路：构建一个二叉树需要构建三部分：root、左子树、右子树；左子树、右子树的构建，又包括：root、左子树、右子树解题关键在于定位出根节点，划分出左右子树，然后 递归 构建左右子树</p>
<p>具体做法：preorder 数组的第一项肯定是根节点 —— 因为前序遍历的顺序是 [根| 左|右 ][根∣左∣右]。由根节点，在 inorder [左 | 根 | 右][左∣根∣右] 中划分出左、右子树的 inorder 序列。<br>通过 inorder 中左右子树的节点个数，在 preorder 中确定左、右子树的 preorder 序列。得到左、右子树的 preorder 和 inorder 序列，就能递归构建左右子树。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> buildTree = <span class="function">(<span class="params">preorder, inorder</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (inorder.length == <span class="number">0</span>) <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">  <span class="keyword">const</span> root = <span class="keyword">new</span> TreeNode(preorder[<span class="number">0</span>]);</span><br><span class="line">  <span class="keyword">const</span> mid = inorder.indexOf(preorder[<span class="number">0</span>]);</span><br><span class="line">  root.left = buildTree(preorder.slice(<span class="number">1</span>, mid + <span class="number">1</span>), inorder.slice(<span class="number">0</span>, mid));</span><br><span class="line">  root.right = buildTree(preorder.slice(mid + <span class="number">1</span>), inorder.slice(mid + <span class="number">1</span>));</span><br><span class="line">  <span class="keyword">return</span> root;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>优化一:字符串截取性能消耗比较大，没必要每次均将preorder、inorder切割；用两个指针表示即可，写一个接受指针的辅助函数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> buildTree = <span class="function">(<span class="params">preorder, inorder</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> helper = <span class="function">(<span class="params">p_start, p_end, i_start, i_end</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (p_start &gt; p_end) <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">let</span> rootVal = preorder[p_start];    <span class="comment">// 根节点的值</span></span><br><span class="line">    <span class="keyword">let</span> root = <span class="keyword">new</span> TreeNode(rootVal);   <span class="comment">// 根节点</span></span><br><span class="line">    <span class="keyword">let</span> mid = inorder.indexOf(rootVal); <span class="comment">// 根节点在inorder的位置</span></span><br><span class="line">    <span class="keyword">let</span> leftNum = mid - i_start;        <span class="comment">// 左子树的节点数</span></span><br><span class="line">    root.left = helper(p_start + <span class="number">1</span>, p_start + leftNum, i_start, mid - <span class="number">1</span>);</span><br><span class="line">    root.right = helper(p_start + leftNum + <span class="number">1</span>, p_end, mid + <span class="number">1</span>, i_end);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> helper(<span class="number">0</span>, preorder.length - <span class="number">1</span>, <span class="number">0</span>, inorder.length - <span class="number">1</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>再次优化：每次递归都要indexof寻找根节点位置，耗费性能；可提前把inorder数组元素和索引存到hash表中。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> buildTree = <span class="function">(<span class="params">preorder, inorder</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; inorder.length; i++) &#123;</span><br><span class="line">    map.set(inorder[i], i);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">const</span> helper = <span class="function">(<span class="params">p_start, p_end, i_start, i_end</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (p_start &gt; p_end) <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">let</span> rootVal = preorder[p_start];    <span class="comment">// 根节点的值</span></span><br><span class="line">    <span class="keyword">let</span> root = <span class="keyword">new</span> TreeNode(rootVal);   <span class="comment">// 根节点</span></span><br><span class="line">    <span class="keyword">let</span> mid = map.get(rootVal);         <span class="comment">// 根节点在inorder的位置</span></span><br><span class="line">    <span class="keyword">let</span> leftNum = mid - i_start;        <span class="comment">// 左子树的节点数</span></span><br><span class="line">    root.left = helper(p_start + <span class="number">1</span>, p_start + leftNum, i_start, mid - <span class="number">1</span>);</span><br><span class="line">    root.right = helper(p_start + leftNum + <span class="number">1</span>, p_end, mid + <span class="number">1</span>, i_end);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> helper(<span class="number">0</span>, preorder.length - <span class="number">1</span>, <span class="number">0</span>, inorder.length - <span class="number">1</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="中序跟后序遍历构造二叉树"><a href="#中序跟后序遍历构造二叉树" class="headerlink" title="中序跟后序遍历构造二叉树"></a>中序跟后序遍历构造二叉树</h2><p>通常从先序序列或者后序序列开始，根据不同遍历方法的规律，选择合适的节点构造树。例如：先序序列的 第一个 节点是根节点，然后是它的左孩子，右孩子等等。后序序列的 最后一个 节点是根节点，然后是它的右孩子，左孩子等等。</p>
<p>从先序/后序序列中找到根节点，根据根节点将中序序列分为左子树和右子树。从中序序列中获得的信息是：如果当前子树为空（返回 None），否则继续构造子树。</p>
<p>创建 hashmap 存储中序序列：value -&gt; its index 。</p>
<p>方法 helper 的参数是中序序列中当前子树的左右边界，该方法仅用于检查子树是否为空。下面分析 helper(in_left = 0, in_right = n - 1) 的逻辑：</p>
<p>1、如果 in_left &gt; in_right，说明子树为空，返回 None。</p>
<p>2、选择后序遍历的最后一个节点作为根节点。</p>
<p>3、假设根节点在中序遍历中索引为 index。从 in_left 到 index - 1 属于左子树，从 index + 1 到 in_right 属于右子树。</p>
<p>4、根据后序遍历逻辑，递归创建右子树 helper(index + 1, in_right) 和左子树 helper(in_left, index - 1)。</p>
<p>5、返回根节点 root</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> buildTree = <span class="function"><span class="keyword">function</span>(<span class="params">inorder, postorder</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> p = i = postorder.length - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">let</span> build = <span class="function">(<span class="params">stop</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(inorder[i] != stop) &#123;</span><br><span class="line">            <span class="keyword">let</span> root = <span class="keyword">new</span> TreeNode(postorder[p--])</span><br><span class="line">            root.right = build(root.val)</span><br><span class="line">            i--</span><br><span class="line">            root.left = build(stop)</span><br><span class="line">            <span class="keyword">return</span> root</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">null</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> build()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="翻转二叉树"><a href="#翻转二叉树" class="headerlink" title="翻转二叉树"></a>翻转二叉树</h2><p>递归三步法：1、确定递归函数的参数和返回值；2、确定终止条件；3、确定单层递归的逻辑。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"> * function TreeNode(val) &#123;</span></span><br><span class="line"><span class="comment"> *     this.val = val;</span></span><br><span class="line"><span class="comment"> *     this.left = this.right = null;</span></span><br><span class="line"><span class="comment"> * &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;TreeNode&#125;</span> <span class="variable">root</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;TreeNode&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> invertTree = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="literal">null</span>) <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">const</span> left = invertTree(root.left);</span><br><span class="line">    <span class="keyword">const</span> right = invertTree(root.right);</span><br><span class="line">    root.left = right;</span><br><span class="line">    root.right = left;</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="将有序数组转换为二叉搜索树"><a href="#将有序数组转换为二叉搜索树" class="headerlink" title="将有序数组转换为二叉搜索树"></a>将有序数组转换为二叉搜索树</h2><p>该解题的本质不在于二叉搜索树和中序遍历，本质是平衡。</p>
<p>如何满足平衡条件：每次把一组数最中间的位置作为树的头拎起来，剩余的部分平均分两份，剩余的一个随便给左子树或右子树；</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">def 做一棵树（数组的哪个段落要做成树）：#这个段落用索引表示即可，与具体数字无关</span><br><span class="line">    #假设这个段落叫A吧</span><br><span class="line">    树的根部 &#x3D; 这个段落A最中间的数字</span><br><span class="line">    树的左边 &#x3D; 做一棵树（这个段落A的左边部分）</span><br><span class="line">    树的右边 &#x3D; 做一棵树（这个段落A的右边部分）</span><br><span class="line">    return 这棵树</span><br></pre></td></tr></table></figure>

<p>二叉搜索树中序遍历后正好是一个递增的数组；因此，其实这个树就是我们中序遍历二叉树的结果。因此我们以和中序遍历相反的方式，从中间开始取root进行构建二叉树即可。</p>
<p>#可以看到整个题解只和index有关，和数组里的具体数字无关，        #因为题目给出的“有序数列”帮助我们满足了“二叉搜索树”的条件。因此只需要操作index来对节点进行重新构建即可。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> sortedArrayToBST = <span class="function">(<span class="params">nums</span>) =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> buildBST = <span class="function">(<span class="params">nums, start, end</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (start &gt; end) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//无符号右移&gt;&gt;&gt;的操作是：丢弃右边指定位数，并左边补上0，因此等于除以2。</span></span><br><span class="line">    <span class="keyword">const</span> mid = (start + end) &gt;&gt;&gt; <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">const</span> root = <span class="keyword">new</span> TreeNode(nums[mid]);</span><br><span class="line"></span><br><span class="line">    root.left = buildBST(nums, start, mid - <span class="number">1</span>);</span><br><span class="line">    root.right = buildBST(nums, mid + <span class="number">1</span>, end);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">  &#125;;</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">return</span> buildBST(nums, <span class="number">0</span>, nums.length - <span class="number">1</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

























<h1 id="二叉树hard题目"><a href="#二叉树hard题目" class="headerlink" title="二叉树hard题目"></a>二叉树hard题目</h1><h2 id="恢复二叉搜索树"><a href="#恢复二叉搜索树" class="headerlink" title="恢复二叉搜索树"></a>恢复二叉搜索树</h2><p>二叉搜索树中的两个节点被错误地交换。</p>
<p>请在不改变其结构的情况下，恢复这棵树。</p>
<p>找到二叉搜索树中序遍历得到值序列的不满足条件的位置。本方法开辟一个新数组 \textit{nums}nums 来记录中序遍历得到的值序列，然后线性遍历找到两个位置 i和 j，并重新遍历原二叉搜索树修改对应节点的值完成修复，</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> inorder = <span class="function">(<span class="params">root, nums</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (root === <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    inorder(root.left, nums);</span><br><span class="line">    nums.push(root.val);</span><br><span class="line">    inorder(root.right, nums);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> findTwoSwapped = <span class="function">(<span class="params">nums</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> n = nums.length;</span><br><span class="line">    <span class="keyword">let</span> x = <span class="number">-1</span>, y = <span class="number">-1</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; n - <span class="number">1</span>; ++i) &#123;</span><br><span class="line">        <span class="keyword">if</span> (nums[i + <span class="number">1</span>] &lt; nums[i]) &#123;</span><br><span class="line">            y = nums[i + <span class="number">1</span>];</span><br><span class="line">            <span class="keyword">if</span> (x === <span class="number">-1</span>) &#123;</span><br><span class="line">                x = nums[i];</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> [x, y];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> recover = <span class="function">(<span class="params">r, count, x, y</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (r !== <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (r.val === x || r.val === y) &#123;</span><br><span class="line">            r.val = r.val === x ? y : x;</span><br><span class="line">            <span class="keyword">if</span> (--count === <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        recover(r.left, count, x, y);</span><br><span class="line">        recover(r.right, count, x, y);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> recoverTree = <span class="function"><span class="keyword">function</span>(<span class="params">root</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> nums = [];</span><br><span class="line">    inorder(root, nums);</span><br><span class="line">    <span class="keyword">const</span> [first, second] = findTwoSwapped(nums);</span><br><span class="line">    recover(root, <span class="number">2</span>, first, second); </span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>


    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2020/09/06/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%AE%97%E6%B3%95/" title="二叉树算法">http://example.com/2020/09/06/算法/二叉树算法/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E7%AE%97%E6%B3%95%E6%A1%86%E6%9E%B6/" rel="tag"># 算法框架</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/09/04/%E5%89%8D%E7%AB%AF/JavaScript%E7%BC%96%E7%A8%8B/" rel="prev" title="JavaScript编程">
      <i class="fa fa-chevron-left"></i> JavaScript编程
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/09/06/C++/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6C/" rel="next" title="深入探究C++">
      深入探究C++ <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#思路指南"><span class="nav-number">1.</span> <span class="nav-text">思路指南</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#数据结构的存储方式"><span class="nav-number">1.1.</span> <span class="nav-text">数据结构的存储方式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#二者优缺点"><span class="nav-number">1.1.1.</span> <span class="nav-text">二者优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基本操作"><span class="nav-number">1.1.2.</span> <span class="nav-text">基本操作</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#medium二叉树刷题（树的核心是递归遍历）"><span class="nav-number">2.</span> <span class="nav-text">medium二叉树刷题（树的核心是递归遍历）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树中序遍历"><span class="nav-number">2.1.</span> <span class="nav-text">二叉树中序遍历</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#前序遍历二叉树"><span class="nav-number">2.2.</span> <span class="nav-text">前序遍历二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后序遍历二叉树"><span class="nav-number">2.3.</span> <span class="nav-text">后序遍历二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#不同的二叉搜索树"><span class="nav-number">2.4.</span> <span class="nav-text">不同的二叉搜索树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#验证二叉搜索树"><span class="nav-number">2.5.</span> <span class="nav-text">验证二叉搜索树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#对称二叉树"><span class="nav-number">2.6.</span> <span class="nav-text">对称二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的BFS与DFS"><span class="nav-number">2.7.</span> <span class="nav-text">二叉树的BFS与DFS</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#层序遍历与最小路径问题"><span class="nav-number">2.8.</span> <span class="nav-text">层序遍历与最小路径问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的锯齿形层次遍历"><span class="nav-number">2.9.</span> <span class="nav-text">二叉树的锯齿形层次遍历</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#前序跟中序遍历构造二叉树"><span class="nav-number">2.10.</span> <span class="nav-text">前序跟中序遍历构造二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#中序跟后序遍历构造二叉树"><span class="nav-number">2.11.</span> <span class="nav-text">中序跟后序遍历构造二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#翻转二叉树"><span class="nav-number">2.12.</span> <span class="nav-text">翻转二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#将有序数组转换为二叉搜索树"><span class="nav-number">2.13.</span> <span class="nav-text">将有序数组转换为二叉搜索树</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二叉树hard题目"><span class="nav-number">3.</span> <span class="nav-text">二叉树hard题目</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#恢复二叉搜索树"><span class="nav-number">3.1.</span> <span class="nav-text">恢复二叉搜索树</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

